package com.lagou.rpc.consumer.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * @description: 客户端业务处理类
 * 1.发送消息
 * 2.处理消息
 * @author: yx
 * @date: 2022/1/11 16:15
 */
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {


    private ChannelHandlerContext channelHandlerContext;

    //发送的消息
    private String requestMsg;

    //服务端响应的消息
    private String responseMsg;

    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }

    /**
     * 通道连接就绪事件
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelHandlerContext = ctx;
    }


    @Override
    //使用notify()必须加锁
    protected synchronized void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        responseMsg = msg;
        //唤醒等待的线程
        notify();
    }

    @Override
    //使用wait()必须加锁
    public synchronized Object call() throws Exception {
        //发送消息
        channelHandlerContext.writeAndFlush(requestMsg);
        //线程等待
        wait();
        return responseMsg;
    }
}
